@push('create_edit_css')
<link rel="stylesheet" href="{{ cdn(elixir('assets/css/fileinput.css')) }}">
<link rel="stylesheet" href="{{ cdn(elixir('assets/css/editor.css')) }}">
<link rel="stylesheet" href="{{ cdn(elixir('assets/css/select2.css')) }}">
@endpush

@push('create_edit_js')
<script src="{{cdn('/assets/js/select2.min.js')}}"></script>
{{--<script src="{{cdn('/assets/js/zh-CN.js')}}"></script>--}}

{{--<script src="{{ cdn(elixir('assets/js/select2.js')) }}"></script>--}}
<script src="{{ cdn(elixir('assets/js/editor.js')) }}"></script>
<script src="{{ cdn(elixir('assets/js/fileinput.js')) }}"></script>
@endpush

@extends('layouts.default')

@section('title')
    {{ isset($topic) ? '编辑话题' : lang('Create New Topic') }}_@parent
@stop

@section('content')

    <div class="topic_create topic-create">

        <div class="col-md-8 col-md-offset-2 main-col">

            <div class="reply-box form box-block">

                {{--<div class="alert alert-warning">--}}
                    {{--{!! lang('be_nice') !!}--}}
                {{--</div>--}}
                <div class="header">
                    上传资源
                </div>

                @include('layouts.partials.errors')

                @if (isset($topic))
                    <form method="POST" action="{{ route('topics.update', $topic->id) }}" accept-charset="UTF-8" id="topic-edit-form" class="topic-form">
                        <input name="_method" type="hidden" value="PATCH">
                        @else
                            <form method="POST" action="{{ route('topics.store') }}" accept-charset="UTF-8" id="topic-create-form" class="topic-form">
                                @endif
                                {!! csrf_field() !!}
                                <div class="oneline-field form-group {{ (!empty($category) && $category->parent_id == 0) ?: 'col-md-4' }} hidden" style="padding-left: 0;" >
                                    <select class="selectpicker form-control" name="parent_category_id" id="parent-category-select" required="required">
                                        <option value="{{ $category->id }}" {{ !empty($category) ?: 'selected' }}>{{ $category->name }}</option>

                                    </select>
                                </div>

                                <div class="oneline-field form-group {{ (!empty($category) && $category->parent_id == 0) ? 'hidden' : '' }} col-md-8" style="padding-right: 0;">
                                    <select class="selectpicker form-control" name="category_id" id="category-select" required="required">

                                        <option value="" disabled {{ !empty($category) ?: 'selected' }}>{{ lang('Pick a son category') }}</option>

                                        @foreach ($categories as $value)
                                            @if($value->id != 3 || Auth::user()->can('compose_announcement'))
                                                @if (
                                                    ($value->id != config('phphub.admin_board_cid') || Auth::user()->can('access_board'))
                                                    && !empty($category)
                                                    && $value->parent_id == $category->parent_id
                                                )
                                                    <option value="{{ $value->id }}" {{ (!empty($category) && $value->id == $category->id) ? 'selected' : '' }} >{{ $value->name }}</option>
                                                @endif
                                            @endif
                                        @endforeach

                                    </select>
                                </div>
                                <div class="clearfix"></div>


                                <div class="form-group">
                                    <input class="form-control" id="topic-title" placeholder="请填写资源名称" name="title" type="text" value="{{ !isset($topic) ? '' : $topic->title }}" required="required">
                                </div>
                                <div id="resource" class="">
                                    <div class="form-group">
                                        <input type="file" id="resource-upload" name="resource">
                                    </div>
                                    <div class="form-group">
                                        <select class="form-control " id="resource-type" name="resource_type">
                                            <option value="" disabled selected>请选择资源类型</option>
                                            @for($i=1; $i <= 4; $i++)
                                                <option value="{{ $i }}" {{ (isset($topic->resource) && $topic->resource->type == $i) ? 'selected' : '' }}>
                                                    @if($i == 1)
                                                        文献
                                                    @elseif($i == 2)
                                                        书籍
                                                    @elseif($i == 3)
                                                        代码
                                                    @elseif($i == 4)
                                                        其他
                                                    @endif
                                                </option>
                                            @endfor
                                        </select>
                                    </div>

                                    <div class="form-group">
                                        <input type="hidden" id="resource-id" name="resource_id" value="{{ isset($topic->resource) ? $topic->resource->id : 0 }}">
                                        <select class="form-control " id="resource-point" name="resource_point">
                                            <option value="" disabled >资源积分</option>
                                            @for($i=1; $i <= 5; $i++)
                                                <option value="{{ $i }}" {{ (isset($topic->resource) && $topic->resource->point == $i) ? 'selected' : '' }}>
                                                    {{ $i }} 积分
                                                </option>
                                            @endfor
                                        </select>
                                    </div>

                                    <div class="form-group">
                                        <select class="form-control " id="resource-category" name="resource_category">
                                            <option value="" disabled selected>请选择资源分类</option>
                                            @for($i=1; $i <= 7; $i++)
                                                <option value="{{ $i }}">

                                                    @if($i == 1)
                                                        基础理论
                                                    @elseif($i == 2)
                                                        语音信号处理
                                                    @elseif($i == 3)
                                                        图像处理
                                                    @elseif($i == 4)
                                                        matlab应用
                                                    @elseif($i == 5)
                                                        python应用
                                                    @elseif($i == 6)
                                                        算法库应用
                                                    @elseif($i == 7)
                                                        其他
                                                    @endif
                                                </option>
                                            @endfor
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <select class="form-control" style="width: 100%" id="tags" name="tags[]" type="text" multiple="multiple">
                                        @foreach($tags as $tag)
                                            <option value="{{ $tag->name }}" {{ isset($topicTags) && in_array($tag->name, $topicTags) ? 'selected' : ''}}>{{ $tag->name }}</option>
                                        @endforeach
                                    </select>
                                </div>

                                @include('topics.partials.composing_help_block')


                                <div class="form-group">
                                    <textarea class="form-control" rows="20" style="overflow:hidden" id="reply_content" placeholder="{{ lang('Please using markdown.') }}" name="body" cols="50">{{ !isset($topic) ? '' : $topic->body_original }}</textarea>
                                </div>

                                <div class="form-group status-post-submit">
                                    <button class="btn btn-primary submit-btn" id="topic-submit" type="submit">{{ lang('Publish') }}</button>
                                </div>

                            </form>
            </div>
        </div>

    </div>

    <script>
        Config.topic_id = '{{ isset($topic) ? $topic->id : 0 }}';
    </script>

@stop


@section('scripts')

    {{--<link rel="stylesheet" href="{{ cdn(elixir('assets/css/editor.css')) }}">--}}
    {{--<link rel="stylesheet" href="{{ cdn(elixir('assets/css/select2.css')) }}">--}}
    {{--<link rel="stylesheet" href="{{ cdn(elixir('assets/css/fileinput.css')) }}">--}}
    {{--<script src="{{ cdn(elixir('assets/js/editor.js')) }}"></script>--}}
    {{--<script src="{{ cdn(elixir('assets/js/select2.js')) }}"></script>--}}
    {{--<script src="{{ cdn(elixir('assets/js/fileinput.js')) }}"></script>--}}
    <style>

        .select2-search__field {
            width: 256px !important;
        }
        .select2-container--default.select2-container--focus {
            box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(0, 181, 173, 0.6);
        }
        .select2-container--default.select2-container--focus .select2-selection--multiple {
            border: solid #00b5ad 1px;
        }
        .select2-container--default .select2-results__option--highlighted[aria-selected] {
            background-color: #00b5ad;
        }
        @media (max-width: 992px) {
            .oneline-field {
                padding: 0;
            }
        }
        .btn {
            margin-top: 1px;
            padding-top: 9px;
            padding-bottom: 9px;
        }
    </style>
    <script type="text/javascript">
        var categories = {!! \App\Models\Category::tree(true) !!};
        var tags = $('#tags');
        var maxTagsSelected = 4;
        var current_cid = $('#parent-category-select').val();
        $(document).ready(function()
        {
            $("#resource-upload").fileinput({
                'language': 'zh',
                'showUpload': true,
                'showPreview': false,
                'maxFileCount': 1,
                'maxFileSize': 61440,
                'uploadExtraData': {'_token': Config.token},
                'uploadUrl': "{{ route('resources.upload') }}"
            }).on('fileuploaded', function (event, data) {
                if (data.response.id !== undefined) {
                    $('#resource-id').val(data.response.id)
                }
            }).on('fileuploaderror', function (event, data, msg) {
                alert(msg);
            });
            tags.select2({
                tags: true,
                tokenSeparators: [',', '，'],
                closeOnSelect: true,
                placeholder: "{{ lang('Input Tags') }}",
                maximumSelectionLength: maxTagsSelected,
                language: 'zh-CN',
                createTag: function(params) {
                    return null;
                }
            });

            $('#topic-submit').on('click', function () {
                if ($('#resource-id').val() == 0) {
                    alert("请选择资源文件并上传!");
                    return false;
                }


                $('#parent_category_id').removeAttr('disabled');
                localStorage.smde_topic_content = ""
            });

            $(document).on('keyup', '.select2-selection--multiple .select2-search__field', function(event){
                if(event.keyCode == 13 || event.keyCode == 188){
                    var $this = $(this);
                    var optionText = $this.val().trim().replace(/[,;，；]*$/, '');
                    if(optionText != "" && $this.find("option[value='" + optionText + "']").length === 0 && tags.find("option[value='" + optionText + "']").length === 0){
                        var $select = $this.parents('.select2-container').prev("select");
                        if (tags.find(":selected").length > maxTagsSelected - 1) {
                            return;
                        }
                        var newOption = new Option(optionText, optionText, true, true);
                        $select.append(newOption).trigger('change');
                        $this.val('');
                    }
                }
            });

            @if ( ! isset($topic))
                localforage.getItem('topic-title', function(err, value) {
                if ($('#topic-title').val() == '' && !err) {
                    $('#topic-title').val(value);
                }
            });
            $('#topic-title').keyup(function(){
                localforage.setItem('topic-title', $(this).val());
            });
            @endif

            $('#parent-category-select').on('change', function(e) {
                current_cid = $(this).val();
                $('.category-hint').hide();
                $('.category-'+current_cid).fadeIn();
                $('#resource').removeClass('hidden')
                $('#resource-type').removeClass('hidden')
                $('#resource-category').removeClass('hidden')
                $('#resource-point').removeClass('hidden')
                $('#resource_dcoin').addClass('hidden')
                $('#algorithm_lang').addClass('hidden')
                $('#algorithm_source_hint').addClass('hidden')

                var subCategorySelect = $("#category-select");
                var parentCategorySelect = $('#parent-category-select');
                // 获取父分类的子分类
                var sons = categories[current_cid].sons;
                if (sons.length === 0) {
                    parentCategorySelect.parent().removeClass('col-md-4');
                    subCategorySelect.parent().addClass('hidden');
                    // 子分类加入值为父分类 ID 的选项并选中
                    subCategorySelect.append("<option value=\""+ current_cid +"\" selected></option>");
                }
                else
                {
                    // 清空子分类选项
                    subCategorySelect.empty();
                    parentCategorySelect.parent().addClass('col-md-4');
                    subCategorySelect.parent().removeClass('hidden');
                    // 子分类加入选项
                    subCategorySelect.append("<option value=\"\" disabled selected>{{ lang('Pick a son category') }}</option>");
                    for (var i in sons)
                    {
                        subCategorySelect.append("<option value=\""+ sons[i].id +"\">"+ sons[i].name +"</option>");
                    }
                }
            });

            // 触发 change 事件
            @if(Route::currentRouteName() == 'topics.create')
                if ($("#parent-category-select").val() !== null)
                {
                    $("#parent-category-select").trigger('change');
                }
            @endif


            var simplemde = new SimpleMDE({
                    spellChecker: false,
                    autosave: {
                        enabled: true,
                        delay: 5000,
                        unique_id: "topic_content{{ isset($topic) ? $topic->id . '_' . str_slug($topic->updated_at) : '' }}"
                    },
                    forceSync: true,
                    tabSize: 4,
                    toolbar: [
                        "bold", "italic", "heading", "|", "quote", "code", "table",
                        "horizontal-rule", "unordered-list", "ordered-list", "|",
                        "link", "image", "|",  "side-by-side", 'fullscreen', "|",
                        {
                            name: "guide",
                            action: function customFunction(editor){
                                var win = window.open('https://github.com/riku/Markdown-Syntax-CN/blob/master/syntax.md', '_blank');
                                if (win) {
                                    //Browser has allowed it to be opened
                                    win.focus();
                                } else {
                                    //Browser has blocked it
                                    alert('Please allow popups for this website');
                                }
                            },
                            className: "fa fa-info-circle",
                            title: "Markdown 语法！",
                        },
                        {
                            name: "publish",
                            action: function customFunction(editor){
                                $('#topic-submit').click();
                            },
                            className: "fa fa-paper-plane",
                            title: "发布文章",
                        }
                    ],
                });

            inlineAttachment.editors.codemirror4.attach(simplemde.codemirror, {
                uploadUrl: Config.routes.upload_image,
                extraParams: {
                    '_token': Config.token,
                },
                onFileUploadResponse: function(xhr) {
                    var result = JSON.parse(xhr.responseText),
                        filename = result[this.settings.jsonFieldName];

                    if (result && filename) {
                        var newValue;
                        if (typeof this.settings.urlText === 'function') {
                            newValue = this.settings.urlText.call(this, filename, result);
                        } else {
                            newValue = this.settings.urlText.replace(this.filenameTag, filename);
                        }
                        var text = this.editor.getValue().replace(this.lastValue, newValue);
                        this.editor.setValue(text);
                        this.settings.onFileUploaded.call(this, filename);
                    }
                    return false;
                }
            });
        });



    </script>
@stop
